<template>
  <div>
    <h2>人脸认证</h2>

    <div v-if="deviceUser">
      <h3>
        {{ deviceUser.username }}
      </h3>

      <br />

      <Image
        :src="require('@/assets/img/faceLogin.png')"
        @click="openFaceCamera"
      />
    </div>

    <div v-else>设备未授权，请使用账号密码登录</div>

    <j-face-camera-dialog
      :dialog="faceCameraDialog"
      @success="captureHandler"
    />
  </div>
</template>
<script>
import JFaceCameraDialog from '@/components/JFaceCamera/JFaceCameraDialog'
import { faceLogin } from '@/api/login'

export default {
  name: 'FaceLogin',
  emits: ['captcha', 'login-success'],
  data() {
    return {
      entity: {
        deviceUid: null,
        userId: null,
      },
      loading: false,
      faceCameraDialog: {
        visible: false,
        value: null,
      },
    }
  },
  computed: {
    device() {
      return this.$store.getters.device
    },
    deviceUser() {
      return this.$store.getters.deviceUser
    },
  },
  components: {
    JFaceCameraDialog,
  },
  methods: {
    openFaceCamera() {
      this.entity.deviceUid = this.device.deviceUid
      this.entity.userId = this.deviceUser.userId
      this.faceCameraDialog.visible = true
    },
    captureHandler() {
      if (!this.faceCameraDialog.value || this.loading) {
        return
      }

      this.loading = true
      faceLogin(this.entity, this.faceCameraDialog.value)
        .then((res) => {
          this.faceCameraDialog.visible = false

          this.$message.success('登录成功')
          this.$emit('login-success', res)
        })
        .catch(() => {
          this.loading = false
        })
    },
  },
}
</script>
